package com.lastproject.ejb.util;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.lastproject.dto.ReviewDTO;
import com.lastproject.ejb.entities.Book;
import com.lastproject.ejb.entities.Review;
import com.lastproject.ejb.entities.User;

/**
 * Session Bean implementation class ReviewConversion
 */
@Stateless
@LocalBean
public class ReviewConversion {

	@PersistenceContext
	EntityManager em;

	public ReviewConversion() {
	}

	public ReviewDTO fromEntity(Review r) {
		ReviewDTO review = new ReviewDTO();
		review.setId(r.getId());
		review.setText(r.getText());
		review.setCountViews(r.getCountViews());
		review.setUserId(r.getUser().getId());
		review.setBookId(r.getBook().getId());

		review.setUserFullName(r.getUser().getFirstname() + " "
				+ r.getUser().getLastname());
		return review;
	}

	public Review fromDTO(ReviewDTO r) {
		Review review = em.find(Review.class, r.getId());
		if (review == null)
			review = new Review();
		review.setText(r.getText());
		review.setCountViews(r.getCountViews());
		review.setUser(em.find(User.class, r.getUserId()));
		review.setBook(em.find(Book.class, r.getBookId()));
		return review;
	}
}
